package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

@RestController
@RequestMapping("/mobile/setmeal")
@Slf4j
public class SetMealController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private SetMealService setMealService;

    /**
     * 查询套餐
     * @return
     */
    @GetMapping("/getSetmeal")
    public Result getSetmeal(){
        //rpc调用查询所有套餐
        try {
            String setmealsList = jedisPool.getResource().get(RedisConst.SETMEALS);
            List<Setmeal> list = null;
            if (null != setmealsList) {
                list = JSON.parseArray(setmealsList, Setmeal.class);
            } else {
                log.info("第一次查询---------[套餐列表]---------从mysql数据库中获取");
                list = setMealService.findAll();
                jedisPool.getResource().setex(RedisConst.SETMEALS, 60 * 60, JSON.toJSONString(list));
            }
            return new Result(true, MessageConst.QUERY_SETMEAL_SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_SETMEAL_FAIL);
        }
    }
    @GetMapping("/findById")
    public Result findById(Integer id){
        //rpc调用查询数据
        try {
            String setmealDetail = jedisPool.getResource().get(RedisConst.SETMEAL + id.toString());
            Setmeal setmeal = null;
            if (setmealDetail==null) {
                log.info("第一次查询---[套餐详情页]----从mysql数据库中获取");
                setmeal = setMealService.findById(id);
                //存放到redis中，拼接上套餐id作为key的唯一标识
                jedisPool.getResource().setex(RedisConst.SETMEAL + id.toString(),60*60,JSON.toJSONString(setmeal));
            }else {
                setmeal = JSON.parseObject(setmealDetail,Setmeal.class);
            }
            return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_SETMEAL_FAIL);
        }
    }
}
